/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pacificlms.MainPanel;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import pacificlms.Email.EmailManager;
import pacificlms.LoggedMember;
import pacificlms.MasterConnection;
import pacificlms.Verifiable.Database.*;
import pacificlms.Verifiable.VerifiableObject;

/**
 *
 * @author Yasir Tanveer
 */
public class ActionCheckInCopyofResource extends CentralUIPanel {

    /**
     * Creates new form ActionCheckInCopyofResource
     */
    public ActionCheckInCopyofResource() {
        super(null);
        initComponents();
    }
    
    @Override
    public String TabName()
    {
        return "Check In";
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        btnClose = new javax.swing.JButton();
        cboStatus = new javax.swing.JComboBox();
        txtConditionFine = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        btnCheckIn = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        txtCallNumber = new javax.swing.JTextField();

        setPreferredSize(new java.awt.Dimension(615, 535));
        setLayout(null);

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 22)); // NOI18N
        jLabel5.setText("Check In");
        add(jLabel5);
        jLabel5.setBounds(10, 0, 85, 31);

        jLabel7.setText("Condition Fine");
        add(jLabel7);
        jLabel7.setBounds(10, 102, 105, 14);

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });
        add(btnClose);
        btnClose.setBounds(505, 501, 100, 23);

        cboStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "returned", "damaged", "lost" }));
        add(cboStatus);
        cboStatus.setBounds(120, 71, 240, 20);

        txtConditionFine.setText("0.00");
        add(txtConditionFine);
        txtConditionFine.setBounds(120, 102, 240, 20);

        jLabel9.setText("Status");
        add(jLabel9);
        jLabel9.setBounds(10, 71, 105, 14);

        btnCheckIn.setText("Check In");
        btnCheckIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckInAction(evt);
            }
        });
        add(btnCheckIn);
        btnCheckIn.setBounds(120, 133, 100, 23);

        jLabel10.setText("Call Number");
        add(jLabel10);
        jLabel10.setBounds(10, 40, 105, 14);
        add(txtCallNumber);
        txtCallNumber.setBounds(120, 40, 240, 20);
    }// </editor-fold>//GEN-END:initComponents

    private Object[] values;    
    private Copy GetCopy()
    {
        try
        {
            Copy Cpy = new Copy();
            String CallNumber = txtCallNumber.getText();
            Cpy.CallNumber(CallNumber);

            String FindCopySQL = Cpy.FindIdenticalSQL();
            Connection Conn = MasterConnection.getInstance();
            Statement stmt = Conn.createStatement();
            ResultSet CopyRS = stmt.executeQuery(FindCopySQL);

            if (!CopyRS.next())
            {
                return null;
            }
            Cpy = (Copy)Copy.CreateFromResultSet(Copy.class, CopyRS, CopyRS.getMetaData());

            return Cpy;
        }
        catch(SQLException Ex)
        {
            return null;
        }
     }
    
    
    void CheckIn()
    {
        String CallNumber = txtCallNumber.getText();
        String Status = cboStatus.getSelectedItem().toString();
        Hold HD = new Hold(),HoldEmail = new Hold();
        //String LibCard = txtMember.getText();
        Member Mem = new Member();
        HoldEmail.RequestDate("2050-01-01");
        String ConditionFine = txtConditionFine.getText();
        
        //check if call number is empty
        if(CallNumber.isEmpty())
        {
            String s="CallNumber can not be empty";
            JOptionPane.showMessageDialog(this,s);
            return;
        }
        try
        { 
            Connection con = MasterConnection.getInstance();
            if(!LoggedMember.getInstance().IsLibrarian())
            {
                JOptionPane.showMessageDialog(null, "Only Librarians can check in items.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }
            Statement stmt = con.createStatement();
            Copy Copy=GetCopy();
            if(Copy==null) 
            {
                JOptionPane.showMessageDialog(null, "No Matched copy.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;
            }
            CheckOut ChOut = new CheckOut();
            ChOut.ResourceCode(Copy.ResourceCode(null));
            ChOut.CopyNumber(Copy.CopyNumber(null));
            ChOut.Finished("0");
            String SQL = ChOut.FindIdenticalSQL();
            ResultSet rs=stmt.executeQuery(SQL);
            GregorianCalendar now= new GregorianCalendar();
            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
            String CurrentDate=sf.format(now.getTime());
            if(!rs.next())
            {
                JOptionPane.showMessageDialog(null, "No Checkouts associated with this call number.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;     
            }
            CheckOut CO = new CheckOut();
            CO = (CheckOut)VerifiableObject.CreateFromResultSet(CheckOut.class, rs, rs.getMetaData());

            if (!Status.equalsIgnoreCase("returned"))
            {
                Copy Cpy = new Copy();//change status of copy
                String CopySQL = Copy.FindIdenticalSQL();
                ResultSet CopyRS = stmt.executeQuery(CopySQL);
                CopyRS.next();
                Cpy = (Copy)VerifiableObject.CreateFromResultSet(Copy.class, CopyRS, CopyRS.getMetaData());
                Cpy.CopyStatus(Status);
                Cpy.Verify();
                CopySQL = Cpy.UpdateRecrodSQL();
                stmt.executeUpdate(CopySQL);
            }
            CO.CheckInDate(sf.format(now.getTime()));
            CO.Finished("1");
            CO.CopyStatus(Status);
            CO.CopyConditionFine(ConditionFine);
            if (!CO.Verify())
                return;
            String CheckInSQL = CO.UpdateRecrodSQL();
            stmt.executeUpdate(CheckInSQL);
            JOptionPane.showMessageDialog(null,"Copy has been checked in successfully ","Success", JOptionPane.INFORMATION_MESSAGE);

            if (HD.EmailNextHolder(CO.ResourceCode(null), stmt))
            {
                JOptionPane.showMessageDialog(null, "There is a hold on this item.", "Hold", JOptionPane.INFORMATION_MESSAGE);
            }
            txtConditionFine.setText("0.00");

        }
        catch(Exception Ex)
        {
            JOptionPane.showMessageDialog(null, "Database error, please try again later\n" + Ex.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        Close();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void CheckInAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheckInAction

        CheckIn();
        
        // TODO add your handling code here:
    }//GEN-LAST:event_CheckInAction

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCheckIn;
    private javax.swing.JButton btnClose;
    private javax.swing.JComboBox cboStatus;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField txtCallNumber;
    private javax.swing.JTextField txtConditionFine;
    // End of variables declaration//GEN-END:variables
}
